package znbkBkfx.BKFX_YDXZ;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.AnswerViewPagerAdapter;
import com.example.znbk.znbklibrary.base.BaseFragment;
import com.lancoo.znbkxx.R;
import com.tt.CoreType;
import com.tt.QType;
import com.tt.SkEgnManager;
import com.tt.listener.OnRecordListener;
import com.tt.widget.AudioRecoderUtils;
import com.tt.widget.JSONTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import znbkBkfx.BkfxActivity;
import znbkBkfx.GetBkfxJson.BkfxPaperEntity;

@SuppressLint("ValidFragment")
public class BkfxYdxzFragment extends BaseFragment {

    private String QuesBody = "";
    private String ChildAsk = "";
    private String SubChildAsk = "";
    private void getEntityInfor(){
        QuesBody = bkfxPaperEntity.getQuesList().get(childIndex).getQuesBody();
        ChildAsk = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().get(0).getChildAsk();
        SubChildAsk = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
    }

    private BkfxPaperEntity bkfxPaperEntity;
    private int childIndex = -1;
    private CallBackFragmentYdxz callBackFragmentYdxz;
    public BkfxYdxzFragment(BkfxPaperEntity bkfxPaperEntity, final int childIndex, CallBackFragmentYdxz callBackFragmentYdxz){
        this.bkfxPaperEntity = bkfxPaperEntity;
        this.childIndex = childIndex;
        this.callBackFragmentYdxz = callBackFragmentYdxz;
        getEntityInfor();
    }

    @Override
    protected int createLayout() {
        return R.layout.bkfx_fragment_ydxz;
    }

    private WebView mWvQuesBody;
    private ViewPager mVpAnswer;
    private ArrayList<View> list;
    private RelativeLayout mRlMyRecordBg;
    private ImageView mIvMyRecordMi;
    private Drawable drawableMi;
    private TextView mTvHintAnswerType;
    public AnswerViewPagerAdapter mAnswerViewPagerAdapter;

    private LinearLayout mLlResultStuScore;
    @Override
    protected void initView(View view) {

        //显示Ask题干
        mWvQuesBody = view.findViewById(R.id.wv_quesBody);
        mWvQuesBody.setBackgroundColor(0); // 设置背景色
        String WvQuesBody = "";
        if (QuesBody.equals("")) {
            if(ChildAsk.equals("")){
                WvQuesBody = SubChildAsk;
            }else{
                WvQuesBody = ChildAsk;
            }
        } else {
            WvQuesBody = QuesBody;
        }
        mWvQuesBody.loadData(WvQuesBody, "text/html", "utf-8");

        //显示Answer信息
        mVpAnswer = view.findViewById(R.id.vp_answerYdxz);
        list = new ArrayList<>();
        list.clear();
        int totalItemCount = bkfxPaperEntity.getQuesList().get(childIndex).getTotalItemCount();
        String typeNo = bkfxPaperEntity.getQuesList().get(childIndex).getTypeInfo().getTypeNo();
        for (int i = 0; i < totalItemCount; i++) {
            RecyclerView mRvAnswer = new RecyclerView(getActivity());
            mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
            BkfxYdxzAnswerAdapter mAnswerAdapter = new BkfxYdxzAnswerAdapter(getActivity(),
                    bkfxPaperEntity,childIndex,i,new BkfxYdxzAnswerAdapter.CallBackAdapterYdxz() {
                @Override
                public void callHideRecordMiView() {
                    hideRecordMiView();
                }

                @Override
                public void callRefreshClickAnswer() {
                    list.clear();
                    int totalItemCountA = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().size();
                    for(int i=0;i<totalItemCountA;i++) {
                        final RecyclerView mRvAnswer = new RecyclerView(getActivity());
                        mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
                        BkfxYdxzAnswerAdapter mAnswerAdapter = new BkfxYdxzAnswerAdapter(getActivity(),
                                bkfxPaperEntity,childIndex,i,new BkfxYdxzAnswerAdapter.CallBackAdapterYdxz() {
                            @Override
                            public void callHideRecordMiView() {
                            }

                            @Override
                            public void callRefreshClickAnswer() {

                            }

                            @Override
                            public void callShowResultStuScore(double stuScore) {

                            }

                        });
                        mRvAnswer.setAdapter(mAnswerAdapter);
                        list.add(mRvAnswer);
                    }
                    mVpAnswer.setAdapter(new AnswerViewPagerAdapter(list));
                    mVpAnswer.setCurrentItem( bkfxPaperEntity.getPaperAnswer().get(childIndex).getCurrentSubChildAnswerIndex());
                }

                @Override
                public void callShowResultStuScore(double stuScore) {
                    showResultStuScore(stuScore);
                }

            });
            mRvAnswer.setAdapter(mAnswerAdapter);
            list.add(mRvAnswer);
        }
        mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
        mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
        bkfxPaperEntity.getPaperAnswer().get(childIndex).setCurrentSubChildAnswerIndex(0);
        mVpAnswer.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                bkfxPaperEntity.getPaperAnswer().get(childIndex).setCurrentSubChildAnswerIndex(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        //显示话咪
        mRlMyRecordBg = view.findViewById(R.id.rl_myRecordBg);
        mRlMyRecordBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                return;
            }
        });
        mIvMyRecordMi = view.findViewById(R.id.iv_myRecordMi);
        drawableMi = mIvMyRecordMi.getDrawable();

        mTvHintAnswerType = view.findViewById(R.id.tv_hintAnswerType);
        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(mTvHintAnswerType,"textColor",0xffffffff,0xffff00aa);
        objectAnimator.setDuration(2000);
        objectAnimator.setRepeatCount(Animation.INFINITE);
        objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
        objectAnimator.start();

        //学生作答得分
        mLlResultStuScore = view.findViewById(R.id.ll_resultStuScore);

    }

    private void showRecordMiView(){
        if(mRlMyRecordBg.getVisibility()==View.GONE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyRecordBg, View.TRANSLATION_Y, 300f, 0f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    mRlMyRecordBg.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }
    private void hideRecordMiView(){
        if(mRlMyRecordBg.getVisibility()==View.VISIBLE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyRecordBg, View.TRANSLATION_Y, 0f, 300f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mRlMyRecordBg.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }


    private Handler mHandler = new  Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if(bkfxPaperEntity!=null) {
                int SubmitState = bkfxPaperEntity.getPaperAnswer().get(childIndex).getSubmitState();
                if (SubmitState != 2) {
                    mRecoderUtils = new AudioRecoderUtils();
                    showRecordMiView();
                    SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                    mRecoderUtils.startRecord();
                }
                mHandler.removeCallbacks(this);
            }else{
                mHandler.post(this);
            }
        }
    };

    public void setUserVisibleHint(boolean isVisibleToUser) {
        int SubmitState = bkfxPaperEntity.getPaperAnswer().get(childIndex).getSubmitState();
        if(isVisibleToUser){
            mHandler.post(mRunnable);
        }else{
            if(SubmitState==2){
                if(mRlMyRecordBg!=null) {
                    mRlMyRecordBg.setVisibility(View.GONE);
                }
            }
        }
    }

    private AudioRecoderUtils mRecoderUtils;
    private String  mCoreType = CoreType.EN_ASR_REC;
    /*
     * 话咪录音操作
     * */
    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
            Log.e("==onRecordingAA==","========vad_status==========="+"121212121212");
        }
        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
            int SubmitState = bkfxPaperEntity.getPaperAnswer().get(childIndex).getSubmitState();
            if(SubmitState==2){
                mIsExitTranslate = true;
                Log.e("==bkfxRecordingAA==", "====dxt====vad_status===========" + vad_status);
                SkEgnManager.getInstance(getActivity()).stopRecord();
                mRecoderUtils.stopRecord();
            }
            Log.e("==onRecordingAA==","========vad_status==========="+vad_status);
            Log.e("==onRecordingBB==","=========sound_intensity==========="+sound_intensity);
            showRecordVolumeSize(sound_intensity);
            if(vad_status==2){
                SkEgnManager.getInstance(getActivity()).stopRecord();
                mRecoderUtils.stopRecord();
            }
        }
        @Override
        public void onRecordEnd(String result) {
            //录制结束
            try {
                final JSONObject json = new JSONObject(result);
                Log.e("17kouyuAAA", "返回json===>" + result);
                String choiceResult = "";
                if(!getResult(result).equals("")) {
                    choiceResult = getResult(result);
                }
                Log.e("==AFGAFG==","========KKKKK》》==========="+choiceResult);
                int SubChildAnsweringIndex = bkfxPaperEntity.getPaperAnswer().get(childIndex).getCurrentSubChildAnswerIndex();//获取当前作答小题的小题编号
                int OptionSize = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().//获取小题对应的选项个数
                        get(SubChildAnsweringIndex).getSubChildList().get(0).getOptionList().size();


                if(choiceResult.equals("a")||choiceResult.equals("hey")||
                        choiceResult.equals("b")||  choiceResult.equals("boy")||
                        choiceResult.equals("c")||
                        choiceResult.equals("d")||choiceResult.equals("dog")){

                    if(choiceResult.equals("a")||choiceResult.equals("hey")){
                        if(OptionSize>=1) {
                            bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("A");
                        }
                    }else if(choiceResult.equals("b")||  choiceResult.equals("boy")){
                        if(OptionSize>=2) {
                            bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("B");
                        }
                    }else if(choiceResult.equals("c")){
                        if(OptionSize>=3) {
                            bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("C");
                        }
                    }else if( choiceResult.equals("d")||choiceResult.equals("dog")){
                        if(OptionSize>=4) {
                            bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("D");
                        }
                    }
                    refreshRecordAnswer();
                }else{
                    if(!mIsExitTranslate) {
                        SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                        mRecoderUtils.startRecord();
                    }
                }


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    private void refreshRecordAnswer(){
        int AnsweredCount=0;
        int AnsweredCountTrue=0;
        int ChildListSize = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().size();
        for(int i=0;i<ChildListSize;i++){
            String StuAnswer =  bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                    get(i).getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
            if(!StuAnswer.equals("")){
                AnsweredCount = AnsweredCount+1;
            }

            String ItemAnswer =  bkfxPaperEntity.getQuesList().get(childIndex).getChildList().
                    get(i).getSubChildList().get(0).getSubChildAnswer();
            if(ItemAnswer.equals(StuAnswer)){
                AnsweredCountTrue = AnsweredCountTrue+1;
            }
        }
        //若作答完成则显示答案，记录作答状态，否则亦然
        if (AnsweredCount == ChildListSize) {
            bkfxPaperEntity.getPaperAnswer().get(childIndex).setSubmitState(2);
            hideRecordMiView();

            double EachScore = 0;
            String QuesList_QuesID = bkfxPaperEntity.getQuesList().get(childIndex).getQuesID();
            int PaperQuesSize = bkfxPaperEntity.getPaperQues().size();
            for(int i=0;i<PaperQuesSize;i++){
                int PaperQues_QuesListSize = bkfxPaperEntity.getPaperQues().get(childIndex).getQuesList().size();
                for(int j=0;j<PaperQues_QuesListSize;j++){
                    String PaperQues_QuesID = bkfxPaperEntity.getPaperQues().get(childIndex).getQuesList().get(j).getQuesID();
                    if(QuesList_QuesID.equals(PaperQues_QuesID)){
                        EachScore = bkfxPaperEntity.getPaperQues().get(childIndex).getEachScore();
                        break;
                    }
                }
            }
            double ResultStuScore = AnsweredCountTrue*EachScore;
            showResultStuScore(ResultStuScore);

        }else{
            bkfxPaperEntity.getPaperAnswer().get(childIndex).setSubmitState(1);
        }
        Log.e("==mAdapter===","=======此处刷新AnswerAdapter============"+"不知道");

        list.clear();
        int totalItemCountA = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().size();
        for(int i=0;i<totalItemCountA;i++) {
            final RecyclerView mRvAnswer = new RecyclerView(getActivity());
            mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
            BkfxYdxzAnswerAdapter mAnswerAdapter = new BkfxYdxzAnswerAdapter(getActivity(),
                    bkfxPaperEntity,childIndex,i,new BkfxYdxzAnswerAdapter.CallBackAdapterYdxz() {
                @Override
                public void callHideRecordMiView() {
//                    hideRecordMiView();
                }

                @Override
                public void callRefreshClickAnswer() {

                }

                @Override
                public void callShowResultStuScore(double stuScore) {

                }


            });
            mRvAnswer.setAdapter(mAnswerAdapter);
            list.add(mRvAnswer);
        }
        mVpAnswer.setAdapter(new AnswerViewPagerAdapter(list));
        mVpAnswer.setCurrentItem( bkfxPaperEntity.getPaperAnswer().get(childIndex).getCurrentSubChildAnswerIndex());

        int SubmitState = bkfxPaperEntity.getPaperAnswer().get(childIndex).getSubmitState();
        if(SubmitState==2){
//            SaveItemQuesAnswer(childIndex);
            SkEgnManager.getInstance(getActivity()).stopRecord();
            mRecoderUtils.stopRecord();
        }else {
            SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
            mRecoderUtils.startRecord();
        }
    }

    private String getResult(String result) {

        String choiceSoundResult = "";
        StringBuilder keyValue = new StringBuilder();
        try{
            JSONObject returnObj = new JSONObject(result);
            JSONObject resultJSONObject = returnObj.getJSONObject("result");
            if(resultJSONObject.has("overall")){
                keyValue.append("总    分: " + resultJSONObject.getString("overall") + "\n");
            }
            Log.e("getResultAAAAA", "====返回json========答案=========>" + resultJSONObject.getString("recognition"));
            choiceSoundResult = resultJSONObject.getString("recognition");
//            notifyDataSetChanged();

        }catch (Exception e){
            e.printStackTrace();
        }
        keyValue.append("\n");
        keyValue.append(JSONTool.stringToJSON(result));

        return choiceSoundResult;
    }


    public interface CallBackFragmentYdxz{
        void pageMoveNext();
    }

    private void showRecordVolumeSize(final int volumesize){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg =Message.obtain();
                msg.obj = volumesize;
                msg.what = 1;
                handler.sendMessage(msg);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int VolumeSize = Integer.valueOf(msg.obj.toString());
                    if(VolumeSize>50){
                        VolumeSize=50;
                    }
                    int LevelSize = VolumeSize*200;
                    drawableMi.setLevel(LevelSize);
                    break;
            }
        }
    };


    private void showResultStuScore(double stuScore){

        String strStuScore = String.valueOf(stuScore);
        if (strStuScore.contains("."))
        {
            String [] newStuScore = strStuScore.split("\\.");
            String front_stuScore = newStuScore[0];
            if(Integer.valueOf(front_stuScore)>=0 && Integer.valueOf(front_stuScore)<=9){
                drawStuScore(front_stuScore);
            }else{
                String str_front_stuScore_0 = front_stuScore.substring(0,1);
                drawStuScore(str_front_stuScore_0);
                String str_front_stuScore_1 = front_stuScore.substring(1,2);
                drawStuScore(str_front_stuScore_1);
            }
            String after_stuScore = newStuScore[1];
            if(Integer.valueOf(after_stuScore)>0){
                ImageView mIv_point = new ImageView(getActivity());
                mIv_point.setImageResource(R.mipmap.stu_score_point);
                mLlResultStuScore.addView(mIv_point);

                ImageView mIv_5 = new ImageView(getActivity());
                mIv_5.setImageResource(R.mipmap.stu_score_5);
                mLlResultStuScore.addView(mIv_5);

            }
        }

        ObjectAnimator translationXShow =  ObjectAnimator.ofFloat(mLlResultStuScore,View.TRANSLATION_X,500f,0f);
        ObjectAnimator alphaShow =  ObjectAnimator.ofFloat(mLlResultStuScore,View.ALPHA,0.6f,1.0f);
        AnimatorSet setShow = new AnimatorSet();
        setShow.playTogether(translationXShow,alphaShow);
        setShow.setInterpolator(new DecelerateInterpolator());
        setShow.setDuration(1600);
        setShow.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mLlResultStuScore.setVisibility(View.VISIBLE);
                BkfxActivity.mVpBkfx.setScrollble(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mLlResultStuScore.setVisibility(View.GONE);
                callBackFragmentYdxz.pageMoveNext();
                BkfxActivity.mVpBkfx.setScrollble(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        setShow.start();

        Log.e("showResultStuScore","=======tlxz=========stuScore==============="+stuScore);

    }

    private void drawStuScore(String score){
        if(score.equals("0")){
            ImageView mIv_0 = new ImageView(getActivity());
            mIv_0.setImageResource(R.mipmap.stu_score_0);
            mLlResultStuScore.addView(mIv_0);
        }else if(score.equals("1")){
            ImageView mIv_1 = new ImageView(getActivity());
            mIv_1.setImageResource(R.mipmap.stu_score_1);
            mLlResultStuScore.addView(mIv_1);
        }else if(score.equals("2")){
            ImageView mIv_2 = new ImageView(getActivity());
            mIv_2.setImageResource(R.mipmap.stu_score_2);
            mLlResultStuScore.addView(mIv_2);
        }else if(score.equals("3")){
            ImageView mIv_3 = new ImageView(getActivity());
            mIv_3.setImageResource(R.mipmap.stu_score_3);
            mLlResultStuScore.addView(mIv_3);
        }else if(score.equals("4")){
            ImageView mIv_4 = new ImageView(getActivity());
            mIv_4.setImageResource(R.mipmap.stu_score_4);
            mLlResultStuScore.addView(mIv_4);
        }else if(score.equals("5")){
            ImageView mIv_5 = new ImageView(getActivity());
            mIv_5.setImageResource(R.mipmap.stu_score_5);
            mLlResultStuScore.addView(mIv_5);
        }else if(score.equals("6")){
            ImageView mIv_6 = new ImageView(getActivity());
            mIv_6.setImageResource(R.mipmap.stu_score_6);
            mLlResultStuScore.addView(mIv_6);
        }else if(score.equals("7")){
            ImageView mIv_7 = new ImageView(getActivity());
            mIv_7.setImageResource(R.mipmap.stu_score_7);
            mLlResultStuScore.addView(mIv_7);
        }else if(score.equals("8")){
            ImageView mIv_8 = new ImageView(getActivity());
            mIv_8.setImageResource(R.mipmap.stu_score_8);
            mLlResultStuScore.addView(mIv_8);
        }else if(score.equals("9")){
            ImageView mIv_9 = new ImageView(getActivity());
            mIv_9.setImageResource(R.mipmap.stu_score_9);
            mLlResultStuScore.addView(mIv_9);
        }
    }

    private boolean mIsExitTranslate = false;
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e("onDestroy","=====fragment=======退出备考复习========mmmm======"+childIndex);
        if(mRecoderUtils!=null) {
            SkEgnManager.getInstance(getActivity()).stopRecord();
            mRecoderUtils.stopRecord();
            mIsExitTranslate = true;
        }
    }

}
